<template>
  <common-edit-dialog :visible="selectUserDialog" :title="'选择人员'" :button-loading="loading"
                      width="1000px" @cancel="cancel" @submit="submit">
    <div class="choose-users-form">
      <div class="dep-tree" v-loading="treeLoading">
        <el-tree slot="group"
                 class="tree mt20"
                 :data="deptSelect"
                 :props="treeProp"
                 default-expand-all
                 :expand-on-click-node="true"
                 :filter-node-method="filterNode"
                 @node-click="handleNodeClick"
                 ref="deptSelect">
          <div style="width: calc(100% - 30px);height:100%;display: flex; align-items: center"
               :class="{'e-t-content': !data.freeze}"
               slot-scope="{ node, data }">
            <common-carousel-text
              :content="node.label"
              :index="node.id"
              :font-size="14">
            </common-carousel-text>
          </div>
        </el-tree>
      </div>

      <div class="user-list">
        <div class="u-l-search">
          <span class="u-l-s-label">用户名</span>
          <common-input v-model="query.userName" clearable/>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        </div>
        <div class="u-l-l" v-loading="tableLoading">
          <common-table slot="content"
                        ref="userList"
                        :data="userList"
                        isSetRowKey
                        :row-key="'userId'"
                        @select="selectionRow"
                        @selection-change="handleSelectionChange">
            <el-table-column type="selection"
                             width="55"
                             align="center"
                             :reserve-selection="true"/>
            <el-table-column label="用户名" align="left" prop="userName"/>
            <el-table-column label="姓名" align="left" prop="nickName"/>
          </common-table>
        </div>
        <pagination slot="pagination"
                    v-show="total>0"
                    :total="total"
                    :page.sync="query.pageNum"
                    :layout="'total, prev, pager, next'"
                    :pagerCount="5"
                    :limit.sync="query.pageSize"
                    @pagination="getUserList"/>
      </div>

      <div class="select-user-list">
        <div class="u-l-search">
          <span class="u-l-s-label">用户名</span>
          <common-input v-model="searchName" clearable/>
          <el-button type="primary" icon="el-icon-search" @click="handleQueryUser">查询</el-button>
        </div>
        <div class="u-l-delete">
          <el-button type="danger" icon="el-icon-delete" plain @click="deleteAll" :disabled="selectedDeleteValue.length === 0">批量解绑</el-button>
          <span>已绑定{{selectedValue.length}}人</span>
        </div>
        <div style="height: 300px;">
          <common-table slot="content"
                        ref="chooseUser"
                        :height="'300px'"
                        @selection-change="handleSelectionChangeUsers"
                        :data="queryData">
            <el-table-column type="selection"
                             width="55"
                             align="center"/>
            <el-table-column label="用户名" align="left" prop="userName"/>
            <!--            <el-table-column label="用户名" align="left" prop="nickName"/>-->
            <el-table-column label="操作" align="left" width="80">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteUser(scope.row,scope.$index)" hasPermi>解绑</el-button>
              </template>
            </el-table-column>
          </common-table>
        </div>

      </div>
    </div>
  </common-edit-dialog>
</template>

<script>
  import {
    user_list,
    dept_select
  } from '@/api/management/usercenter/user.js'
  import {
    batchDeleteUserRole,
    batchAddUserRole,
    selectUsersByRoles
  } from '@/api/system/user'
  import { deepClone } from '@/utils'

  export default {
    name: 'userAdd',
    data() {
      return {
        selectUserDialog: false,
        isEdit: false,
        loading: false,
        deptSelect: [], // 菜单树
        treeProp: {
          // 树参数
          children: 'children',
          label: 'label'
        },
        query: {
          pageNum: 1,
          pageSize: 5,
          userName: null,
          nickName: null,
          status: null
        }, // 查询条件
        treeLoading: false,
        tableLoading: false,
        userList: [],
        total: 1,
        selectedValue: [], //已选择人员
        roleId: '',
        showList: [],
        searchName: '',
        selectedDeleteValue: [],
        queryData: [],
      }
    },
    methods: {
      cancel() {
        this.selectUserDialog = false
      },
      show(data) {
        this.roleId = data.roleId ? data.roleId : '';
        this.query.pageNum = 1;
        this.query.pageSize = 5;
        this.query.deptId = '';
        this.query.nickName = null;
        this.query.userName = null;
        this.selectedValue = [];
        this.userList = [];
        this.selectUserDialog = true
        this.treeLoading = true
        this.getSelectedUsers()
        this.getDeptSelect()
        this.getUserList()
      },
      /**
       * 获取菜单树
       */
      getDeptSelect() {
        dept_select({}).then((res) => {
          this.deptSelect = res.data
        }).finally(() => this.treeLoading = false)
      },
      /**
       * 获取已选人员
       */
      getSelectedUsers() {
        selectUsersByRoles([this.roleId]).then((res) => {
          this.showList = deepClone(res.data)
          this.userList.forEach(item => {
            if (res.data.find(f => f.userId === item.userId)) {
              item.checked = true
              this.$refs.userList.$refs.table.toggleRowSelection(item, true)
            } else {
              // this.$refs.userList.$refs.table.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedValue = res.data
            this.queryData = this.selectedValue
          })
        }).finally(() => {
          this.treeLoading = false
        })
      },
      /**
       * 点击菜单获取数据
       */
      handleNodeClick(data) {
        this.query.pageNum = 1;
        this.query.pageSize = 5;
        this.query.deptId = data.id;
        this.query.nickName = null;
        this.query.userName = null;
        this.getUserList()
      },
      /**
       * 过滤
       */
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      handleQuery() {
        this.query.pageNum = 1
        this.getUserList()
      },
      /**
       * 获取人员列表
       */
      getUserList() {
        this.tableLoading = true
        let query = { ...this.query }
        user_list(query).then((res) => {
          this.userList = res.rows
          this.total = res.total


          this.$nextTick(() => {
            this.userList.map(item => {
              this.selectedValue.map(val => {
                if (item.userId === val.userId) {
                  setTimeout(() => {
                    // console.log(this.$refs.userList)
                    this.$refs.userList.$refs.table.toggleRowSelection(item, true);
                  }, 300);
                }
              })
            })
          })

        }).finally(() => this.tableLoading = false)
      },
      selectionRow(val) {
        // this.selectedValue = row
        if(val.data) {
          let index = this.selectedValue.findIndex(v => v.userId === val.data.userId)
          if(index > -1) {
            this.selectedValue.splice(index,1)
          }
        }
        this.queryData = this.selectedValue
        // console.log(row)
      },
      /**
       * 选择人员
       */
      handleSelectionChange(val,row) {
        let data = []
        val.forEach(f => {
          if(this.selectedValue.findIndex(v => v.userId === f.userId) === -1) {
            this.selectedValue.push(f)
          }
          if(this.userList.filter(p => p.userId === f.userId).length > 0) {
            data = this.userList.filter(p => p.userId === f.userId)
          }
        })

        if(data.length === 0) {
          this.userList.forEach(f => {
            let index = this.selectedValue.findIndex(v => v.userId === f.userId)
            if(index > -1) {
              this.selectedValue.splice(index, 1)
            }
          })
        }
        this.queryData = this.selectedValue
      },
      /**
       * 删除人员
       * @param row
       * @param index
       */
      deleteUser(row, index) {
        let ids = this.$refs.userList.$refs.table.selection.findIndex(f => f.userId === row.userId)
        if(ids > -1) {
          this.$refs.userList.$refs.table.selection.splice(ids, 1)
        }
        this.selectedValue.splice(index, 1)
        this.queryData = this.selectedValue
      },
      submit() {
        let userIds = this.selectedValue.reduce((r, c) => {
          r.push(c.userId)
          return r
        }, [])
        this.loading = true
        let params = {
          roleId: this.roleId,
          userIds: userIds.join(',')
        }
        batchAddUserRole(params).then(res => {
          if(res && res.code === 200) {
            this.$GlobalSuccessMessage("新增成功");
            this.selectUserDialog = false
            this.$emit('refresh')
          } else {
            this.$GlobalErrorConfirm('新增失败', res.msg).then()
          }
        }).finally(() => this.loading = false)
      },
      selectable(row,index) {
        return !this.selectedValue.some(f => f.userId === row.userId);
      },
      /**
       * 已选用户筛选
       */
      handleQueryUser() {
        if(this.searchName) {
          this.queryData = this.selectedValue.filter(f => f.userName.includes(this.searchName))
        } else {
          this.queryData = this.selectedValue
        }
      },
      handleSelectionChangeUsers(val) {
        this.selectedDeleteValue = val
      },
      /**
       * 删除已选用户
       */
      deleteAll() {
        this.selectedDeleteValue.forEach(f => {
          let index = this.selectedValue.findIndex(v => v.userId === f.userId)
          if(index > -1) {
            this.selectedValue.splice(index, 1)
          }
          let ids = this.$refs.userList.$refs.table.selection.findIndex(v => v.userId === f.userId)
          if(ids > -1) {
            this.$refs.userList.$refs.table.selection.splice(ids, 1)

          }
        })
        this.selectedDeleteValue = []
        this.$refs.chooseUser.$refs.table.clearSelection();
        this.queryData = this.searchName ? this.selectedValue.filter(f => f.userName === this.searchName) : this.selectedValue
      },
    },
    mounted() {
      // this.getDeptSelect()
    }
  }
</script>

<style scoped lang="scss">

  .choose-users-form {
    display: flex;

    .dep-tree {
      width: 200px;
      border-right: 1px solid #eee;
      height: 376px;
      overflow-y: scroll;
    }

    .user-list {
      width: 380px;
      border-right: 1px solid #eee;
    }

    .u-l-search {
      display: flex;
      align-items: center;
      padding-left: 20px;
      margin-bottom: 12px;

      .u-l-s-label {
        width: 60px;
      }

      .el-input {
        width: 160px;
        margin-right: 20px;
      }
    }

    .u-l-delete {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 17px;
      .el-button {
        margin-left: 20px;
      }
    }

    .u-l-l {
      /*min-height: 250px;*/
      height: 286px;
    }

    .select-user-list {
      width: 380px;
      box-sizing: border-box;

      .u-l-search {
        height: 32px;
        line-height: 32px;
        margin-bottom: 12px;
      }
    }
  }

</style>
